package com.xiaow.springsecuriydemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaow.springsecuriydemo.entity.Goods;
import com.xiaow.springsecuriydemo.entity.Trading;
import com.xiaow.springsecuriydemo.service.GoodsService;
import com.xiaow.springsecuriydemo.service.TradingService;
import com.xiaow.springsecuriydemo.utils.JwtUtils;
import com.xiaow.springsecuriydemo.vo.*;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xiaow
 * @since 2022-09-17
 */
@RestController
@RequestMapping("/trading")
public class TradingController {

    @Autowired
    GoodsService goodsService;


    @Autowired
    TradingService tradingService;

    /**
     * 购买商品接口
     *
     * @return
     */
    @PostMapping("/buyGoods")
    @PreAuthorize("hasAuthority('/user')")
    @Transactional
    public Result buyGoods(@RequestBody Trading trading, HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        if (Strings.isEmpty(token)) {
            return Result.result("请先登录", 401, "");
        }
        Claims claims = JwtUtils.getClaims(token);
        String userid = (String) claims.get("userid");
        trading.setUserid(Long.parseLong(userid))
                .setCtime(LocalDateTime.now())
                .setStatus(0)
                .setId(0);
        Goods byId = goodsService.getById(trading.getGoodsid());
        int num = (int) (trading.getMoney() / byId.getMoney());
        if (byId.getRemaining() < num) {
            return Result.fail("库存不足");
        }
        byId.setRemaining(byId.getRemaining() - num);
        boolean b = goodsService.updateById(byId);
        boolean save = tradingService.save(trading);
        if (save && b)
            return Result.succ("购买成功");
        else
            return Result.fail("下单失败");

    }


    @GetMapping("/geTradingByUserId")
    @PreAuthorize("hasAuthority('/user')")
    public Result geTradingByUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<TradingVo> list = tradingService.getByUserId(loginUser.getUser().getId());
        System.out.println(list);
        return Result.succ(list);
    }

    /**
     * 根据商家id获取订单
     *
     * @param shopid
     * @param page
     * @param shopid 店铺名称
     * @return
     */
    @GetMapping("/getByShopId")
    @PreAuthorize("hasAuthority('/shoper')")
    public LayuiPageResult getByShopId(@RequestParam(name = "shopid") Integer shopid, @RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "limit", defaultValue = "10") Integer limit) {
        IPage<TradingVo2> p = new Page<>(page, limit);
        IPage<TradingVo2> byShopId = tradingService.getByShopId(shopid, p);
//        IPage<TradingVo2> byShopId = tradingService.pageByHot(p);
        LayuiPageResult succ = new LayuiPageResult()
                .setMsg("成功")
                .setData(byShopId.getRecords())
                .setCode(0)
                .setCount(byShopId.getTotal());
        return succ;
    }

    /**
     * 用户退货
     *
     * @param tradingId
     * @return
     */
    @PostMapping("/userReturnGoods")
    @PreAuthorize("hasAnyAuthority('/user','/shoper')")
    public Result userReturnGoods(@RequestParam("tradingid") Integer tradingId) {
        boolean b = tradingService.updateById(new Trading().setStatus(2).setId(tradingId));
        if (b)
            return Result.succ("处理中，请稍后");
        return Result.fail("退货失败，请重试");
    }


    @GetMapping("/getReturnApply")
    @PreAuthorize("hasAuthority('/shoper')")
    public LayuiPageResult getReturnApply(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "limit", defaultValue = "10") Integer limit, @RequestParam(name = "shopid") Integer shopid) {
        IPage<TradingVo2> p = new Page<>(page, limit);
        IPage<TradingVo2> returnApply = tradingService.getReturnApply(p, shopid);
        LayuiPageResult succ = new LayuiPageResult()
                .setMsg("成功")
                .setData(returnApply.getRecords())
                .setCode(0)
                .setCount(returnApply.getTotal());
        return succ;
    }

}
